import db from '@/mock/createDB'
import Mock from 'mockjs'

// 部门列表查询
Mock.mock('/departments/query', 'post', ({ body }) => {
  let {pageNo, pageSize, departmentName } = JSON.parse(body);
  // 数字的转为数字
  pageNo = +pageNo;
  pageSize = +pageSize;
  // 处理中文乱码问题
  departmentName = departmentName ? decodeURIComponent(departmentName) : departmentName;
  
  // 先搜索（模糊搜索)
  const searchResult = db.select('departments_table', (item:any) => {
    return (item.departmentName.includes(departmentName) || !departmentName);
  })

  // 后分页
  const total = searchResult.length;
  const totalPage = Math.ceil(total / pageSize);
  if (pageNo > totalPage) pageNo = totalPage;
  const start = (pageNo - 1) * pageSize;
  const end = start + pageSize;
  // 搜索的结果切合分页
  const pageResult = searchResult.slice(start, end);
  return { code: 0, message: '查询成功', data: {pageNo, pageSize, total, dataLists:pageResult} }
})

// 所有部门查询
Mock.mock('/departments/all', 'get', () => {
  const result = db.select('departments_table', (item:any) => {
    return true;
  })
  return { code: 0, message: '查询成功', data: result }
})

// 添加部门
Mock.mock('/departments/create', 'post', ({ body }) => {
  let { departmentName, directorId, phoneNum, email, departmentDesc } = JSON.parse(body)
  // 数字的转为数字
  directorId = +directorId;
  const nameRepeat = db.select('departments_table', (item:any) => item.departmentName === departmentName)
  // 判断部门名是否存在
  if (nameRepeat && nameRepeat.length) {
    return {
      code: 1009,
      message: '该部门已存在'
    }
  }
  const mobileRepeat = db.select('departments_table', (item:any) => item.phoneNum === phoneNum && phoneNum)
  // 判断手机号是否被使用
  if (mobileRepeat && mobileRepeat.length) {
    return {
      code: 1004,
      message: '手机号码已经被注册，请重新输入'
    }
  }
  db.add('departments_table', { departmentName, directorId, phoneNum, email, departmentDesc, members: 0 })
  return {
    code: 0,
    message: '添加成功'
  }
})

// 修改部门
Mock.mock('/departments/modify', 'post', ({ body }) => {
  let { id, departmentName,  directorId, phoneNum, email, departmentDesc } = JSON.parse(body);
  // 数字的转为数字
  id = +id;
  directorId = +directorId;
  const result = db.select('departments_table', item => item.id === id)[0];
  const { phoneNum: _phoneNum } = result;
  const mobileRepeat = db.select('departments_table', (item:any) => item.phoneNum === phoneNum && item.phoneNum !== _phoneNum && phoneNum);
  // 判断手机号是否被使用
  if (mobileRepeat && mobileRepeat.length) {
    return {
      code: 1004,
      message: '手机号码已经被注册，请重新输入'
    }
  }
  const row = { id, departmentName,  directorId, phoneNum, email, departmentDesc }
  db.put('departments_table', id, row)
  return {
    code: 0,
    message: '修改成功'
  }
})

// 删除部门
Mock.mock('/departments/delete', 'post', ({ body }) => {
  const { ids } = JSON.parse(body);
  if(ids.length == 0) {
    return {
      code: 1005,
      message: '至少选择一个用户'
    }
  }
  db.delete('departments_table', ids)
  return {
    code: 0,
    message: '删除成功'
  }
})
